package com.youlai.system.plugin.easyexcel;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.youlai.system.model.entity.SysDept;
import com.youlai.system.model.entity.SysRole;
import com.youlai.system.model.entity.SysUser;
import com.youlai.system.model.vo.TeacherImportVO;
import com.youlai.system.service.SysDeptService;
import com.youlai.system.service.SysRoleService;
import com.youlai.system.service.SysUserRoleService;
import com.youlai.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * 内训师Excel导入监听器
 */
@Slf4j
public class TeacherImportListener extends MyAnalysisEventListener<TeacherImportVO> {

    private final SysDeptService deptService;

    private final SysRoleService roleService;

    private final SysUserService userService;
    private final SysUserRoleService userRoleService;

    // 部门ID
    private final Long deptId;

    public TeacherImportListener(Long deptId) {
        this.deptId = deptId;
        this.deptService = SpringUtil.getBean(SysDeptService.class);
        this.userService = SpringUtil.getBean(SysUserService.class);
        this.userRoleService = SpringUtil.getBean(SysUserRoleService.class);
        this.roleService = SpringUtil.getBean(SysRoleService.class);
    }

    public TeacherImportListener(SysDeptService deptService, SysRoleService roleService, SysUserService userService, SysUserRoleService userRoleService, Long deptId) {
        this.deptService = deptService;
        this.roleService = roleService;
        this.userService = userService;
        this.userRoleService = userRoleService;
        this.deptId = deptId;
    }

    @Override
    public String getMsg() {
        // 总结信息
        String summaryMsg = StrUtil.format("导入内训师结束：成功{}条，失败{}条；<br/>{}", validCount, invalidCount, msg);
        return summaryMsg;
    }

    @Override
    public void invoke(TeacherImportVO teacherImportVO, AnalysisContext analysisContext) {
        log.info("解析到一条内训师数据:{}", JSONUtil.toJsonStr(teacherImportVO));
        // 校验数据
        StringBuilder validationMsg = new StringBuilder();

        if (StrUtil.isBlank(teacherImportVO.getDeptName())) {
            validationMsg.append("部门为空");
        }

        if (StrUtil.isBlank(teacherImportVO.getAccount())) {
            validationMsg.append("工号为空");
        }

        if (StrUtil.isBlank(teacherImportVO.getName())) {
            validationMsg.append("姓名为空");
        }
        //默认为教师角色(内训师)
        SysRole role = roleService.getTeacherRole();
        if (role == null) {
            validationMsg.append("没有找到指定的内训师角色，请先到角色管理添加code为[TEACHER]的内训师角色");
        }

        if (validationMsg.isEmpty()) {
            SysDept dept = deptService.getDeptBy(this.deptId, teacherImportVO.getDeptName());
            if (dept == null) {
                SysDept parent = deptService.getById(this.deptId);
                validationMsg.append("没有在指定的父部门【" + parent + "】下找到名称为【" + teacherImportVO.getDeptName() + "】子部门");
                invalidCount++;
                msg.append("第" + (validCount + invalidCount) + "行数据执行失败：").append(JSONUtil.toJsonStr(teacherImportVO)).append(validationMsg + "<br/>");
            } else {
                SysUser user = userService.getByAccount(teacherImportVO.getAccount());
                if (user == null) {
                    user = userService.saveTeacher(teacherImportVO.getAccount(), teacherImportVO.getName(), dept.getId());
                } else {
                    user.setNickname(teacherImportVO.getName());
                    user.setDeptId(dept.getId());
                }

                if (!userRoleService.hasAssignedRole(user.getId(), role.getId())) {
                    userRoleService.saveUserRoles(user.getId(), Arrays.asList(role.getId()));
                }
                userService.updateById(user);
                validCount++;
            }

        } else {
            invalidCount++;
            msg.append("第" + (validCount + invalidCount) + "行数据校验失败：").append(JSONUtil.toJsonStr(teacherImportVO)).append(validationMsg + "<br/>");
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
